#ifndef __SOFTPOINTPWM_H__
#define __SOFTPOINTPWM_H__

#include "plat/nonecopyable.h"
#include "soc/soc_timer.h"
#include "soc/soc_gpio.h"
#include "softpwmitem.h"

#define SOFT_PWM_POINT_MAX 4

/// @brief 软件pwm
///        采用定时器匹配点模式
///        最大性能取决于MCU主频
///        采用一个定时器一个比较通道，对应一路PWM
class SoftPointPwm : public NoneCopyable
{
public:
    explicit SoftPointPwm();
    virtual ~SoftPointPwm();

public:
    void AttachTimer(SOC_Timer *timer);
    void DettachTimer();

    void AttachGpio(int ch, const GpioPortPin &gpio, const GpioPortPin &gpioN = GpioPortPin::None());
    void DettachGpio(int ch);

    void Config(int ch, bool isReverse, int normalValue = 0, bool isSameWhenNormal = true);

    void SetPeriod(int period); //一个timer，只有一个period
    int GetPeriod();
    /// @brief 必须先设置周期，才能设置duty
    /// @param ch 
    /// @param duty 
    void SetDuty(int ch, int duty);
    int GetDuty(int ch);

    bool IsRunning(int ch);

    void Start(int ch);
    void Start(int ch, int periodCount);
    void StartAll();
    void Stop(int ch);
    void StopAll();

private:
    void TimerHandler(int channel);
    void SetPeriodNoTimer(int period);

private:
    SoftPwmItem m_pwmItems[SOFT_PWM_POINT_MAX];
    //使用定时器匹配中断
    SOC_Timer *m_timer = nullptr;
    int m_timerPeriod = 0;
    int m_PeriodCountMax = -1; //多少个周期后自动停止pwm,-1为永远运行
};

#endif // __SOFTPOINTPWM_H__
